package com.rapida.framwork;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.lang.reflect.Field;

/**
 * Created by mm on 14-12-17.
 */
public abstract class RapidActivity extends BaseActivity {
    private UIViewController mUIController;
    protected abstract boolean didFinishLaunchingWithOptions();

    @Override
    protected final void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (didFinishLaunchingWithOptions() && mUIController != null) {
            registerViewEvent(mUIController, getWindow().getDecorView());
            mUIController.viewDidLoad();
        }
    }

    public void setViewController(UIViewController uiController) {
        mUIController = uiController;
        registerViewLayout(mUIController);
    }

    private void registerViewLayout(Object classObj) {
        IVOutlet layout = classObj.getClass().getAnnotation(IVOutlet.class);
		if (layout != null) {
			int layoutId = layout.id();
			setContentView(layoutId);
		}
    }

	private void registerViewEvent(Object classObj, View rootView) {
		Field[] fields = classObj.getClass().getDeclaredFields();
		if (fields != null && fields.length > 0) {
			for (Field field : fields) {
				try {
					field.setAccessible(true);
					if (field.get(classObj) != null) {
						continue;
					}
					IBOutlet outlet = field.getAnnotation(IBOutlet.class);
					if (outlet != null) {
						int viewId = outlet.id();
						field.set(classObj, rootView.findViewById(viewId));
					}
				} catch (Exception e) {
					Log.d("Rapid", "registerViewEvent exception");
				}
			}
		}
	}
}
